package junior.db.mapping;

import javax.persistence.Table;
import java.util.HashMap;
import java.util.Map;

public class AnnotationTableMapping implements TableMapping {
	private Map<String, Class<?>> tableMapping = new HashMap<String, Class<?>>();
	private Map<Class<?>, String> entityMapping = new HashMap<Class<?>, String>();
	private TableMapping tableMapper;
	
	public AnnotationTableMapping(TableMapping tableMapper) {
		this.tableMapper = tableMapper;
	}

	@Override
	public String entity2TableName(Class<?> entityClass) {
		String tableName = entityMapping.get(entityClass);
		
		if (tableName == null) {
			Table table = entityClass.getAnnotation(Table.class);
			if (table != null) {
				tableName = table.name();
				entityMapping.put(entityClass, tableName);
			} else {
				tableName = tableMapper.entity2TableName(entityClass);
			}
			
			tableMapping.put(tableName, entityClass);
		}
		
		return tableName;
	}
	
	@Override
	public String tableName2EntityName(String tableName) {
		Class<?> clazz = tableMapping.get(tableName);
		if (clazz == null) {
			return tableMapper.tableName2EntityName(tableName);
		}
		return clazz.getSimpleName();
	}

	public TableMapping getTableMapper() {
		return tableMapper;
	}
}
